<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品类别" prop="productCategory">
        <el-select v-model="queryParams.productCategory" placeholder="请选择产品类别" clearable>
          <el-option
            v-for="dict in ncpsy_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品种" prop="variety">
        <el-select v-model="queryParams.variety" placeholder="请选择品种" clearable>
          <el-option
            v-for="dict in ncpsy_product_variety"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="农产品种植备案号" prop="plantingRecordNumber">
        <el-input
          v-model="queryParams.plantingRecordNumber"
          placeholder="请输入农产品种植备案号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in ncpsy_permitted_product_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ncpsy:permit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ncpsy:permit:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ncpsy:permit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ncpsy:permit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="permitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键产品ID" align="center" prop="productId" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品类别" align="center" prop="productCategory">
        <template #default="scope">
          <dict-tag :options="ncpsy_category" :value="scope.row.productCategory"/>
        </template>
      </el-table-column>
      <el-table-column label="品种" align="center" prop="variety">
        <template #default="scope">
          <dict-tag :options="ncpsy_product_variety" :value="scope.row.variety"/>
        </template>
      </el-table-column>
      <el-table-column label="种植周期(天)" align="center" prop="plantingCycle" />
      <el-table-column label="所属用户ID" align="center" prop="userId" />
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template #default="scope">
          <dict-tag :options="ncpsy_permitted_product_status" :value="scope.row.auditStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="reviewer" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ncpsy:permit:edit']">修改</el-button>
          <el-button link type="primary" icon="View" @click="handleAudit(scope.row)" v-hasPermi="['ncpsy:permit:audit']">审核</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ncpsy:permit:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改准许种植产品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="permitRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品类别" prop="productCategory">
          <el-select v-model="form.productCategory" placeholder="请选择产品类别">
            <el-option
              v-for="dict in ncpsy_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品种" prop="variety">
          <el-select v-model="form.variety" placeholder="请选择品种">
            <el-option
              v-for="dict in ncpsy_product_variety"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="种植周期(天)" prop="plantingCycle">
          <el-input-number v-model="form.plantingCycle" :min="1" placeholder="请输入种植周期" />
        </el-form-item>
        <el-form-item label="农产品种植备案号" prop="plantingRecordNumber">
          <el-input v-model="form.plantingRecordNumber" placeholder="请输入备案号" />
        </el-form-item>
        <el-form-item label="适宜土地" prop="suitableLand">
          <el-input v-model="form.suitableLand" placeholder="请输入适宜土地类型" />
        </el-form-item>
        <el-form-item label="适宜温度" prop="suitableTemperature">
          <el-input v-model="form.suitableTemperature" placeholder="请输入适宜温度范围" />
        </el-form-item>
        <el-form-item label="适宜月份" prop="suitableMonths">
          <el-input v-model="form.suitableMonths" placeholder="请输入适宜种植月份" />
        </el-form-item>
        <el-form-item label="注意事项" prop="precautions">
          <el-input v-model="form.precautions" type="textarea" placeholder="请输入注意事项" />
        </el-form-item>
        <el-form-item label="追加事项" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入追加事项" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog title="产品审核" v-model="auditOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="产品ID">{{ auditForm.productId }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ auditForm.productName }}</el-descriptions-item>
        <el-descriptions-item label="所属用户ID">{{ auditForm.userId }}</el-descriptions-item>
        <el-descriptions-item label="产品类别">
          <dict-tag :options="ncpsy_category" :value="auditForm.productCategory"/>
        </el-descriptions-item>
        <el-descriptions-item label="品种">
          <dict-tag :options="ncpsy_product_variety" :value="auditForm.variety"/>
        </el-descriptions-item>
        <el-descriptions-item label="种植周期(天)">{{ auditForm.plantingCycle }}</el-descriptions-item>
        <el-descriptions-item label="农产品种植备案号">{{ auditForm.plantingRecordNumber }}</el-descriptions-item>
        <el-descriptions-item label="适宜土地">{{ auditForm.suitableLand }}</el-descriptions-item>
        <el-descriptions-item label="适宜温度">{{ auditForm.suitableTemperature }}</el-descriptions-item>
        <el-descriptions-item label="适宜月份">{{ auditForm.suitableMonths }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <dict-tag :options="ncpsy_permitted_product_status" :value="auditForm.auditStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="审核人">{{ auditForm.reviewer }}</el-descriptions-item>
        <el-descriptions-item label="审核人ID">{{ auditForm.reviewerId }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(auditForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(auditForm.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="注意事项" :span="2">{{ auditForm.precautions }}</el-descriptions-item>
        <el-descriptions-item label="追加事项" :span="2">{{ auditForm.description }}</el-descriptions-item>
      </el-descriptions>
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef" label-width="80px">
        <el-form-item label="审核意见" prop="rejectReason">
          <el-input v-model="auditForm.rejectReason" type="textarea" placeholder="请输入审核意见" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitAudit('审核通过')">审核通过</el-button>
          <el-button type="danger" @click="submitAudit('审核驳回')">审核驳回</el-button>
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品详情对话框 -->
    <el-dialog title="产品详情" v-model="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="产品ID">{{ detailForm.productId }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ detailForm.productName }}</el-descriptions-item>
        <el-descriptions-item label="所属用户ID">{{ detailForm.userId }}</el-descriptions-item>
        <el-descriptions-item label="产品类别">
          <dict-tag :options="ncpsy_category" :value="detailForm.productCategory"/>
        </el-descriptions-item>
        <el-descriptions-item label="品种">
          <dict-tag :options="ncpsy_product_variety" :value="detailForm.variety"/>
        </el-descriptions-item>
        <el-descriptions-item label="种植周期(天)">{{ detailForm.plantingCycle }}</el-descriptions-item>
        <el-descriptions-item label="农产品种植备案号">{{ detailForm.plantingRecordNumber }}</el-descriptions-item>
        <el-descriptions-item label="适宜土地">{{ detailForm.suitableLand }}</el-descriptions-item>
        <el-descriptions-item label="适宜温度">{{ detailForm.suitableTemperature }}</el-descriptions-item>
        <el-descriptions-item label="适宜月份">{{ detailForm.suitableMonths }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <dict-tag :options="ncpsy_permitted_product_status" :value="detailForm.auditStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="审核人">{{ detailForm.reviewer }}</el-descriptions-item>
        <el-descriptions-item label="审核人ID">{{ detailForm.reviewerId }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detailForm.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="注意事项" :span="2">{{ detailForm.precautions }}</el-descriptions-item>
        <el-descriptions-item label="追加事项" :span="2">{{ detailForm.description }}</el-descriptions-item>
        <el-descriptions-item label="审核意见" :span="2">{{ detailForm.rejectReason }}</el-descriptions-item>

      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDetail">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Permit">
import { listPermit, getPermit, delPermit, addPermit, updatePermit } from "@/api/ncpsy/management/permit"
import useUserStore from "@/store/modules/user"

const { proxy } = getCurrentInstance()
const { ncpsy_category, ncpsy_permitted_product_status,ncpsy_product_variety } = proxy.useDict('ncpsy_category', 'ncpsy_permitted_product_status','ncpsy_product_variety')
const userStore = useUserStore()

// 时间格式化函数
function parseTime(time, pattern) {
  if (!time) return null
  const date = new Date(time)
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

const permitList = ref([])
const open = ref(false)
const auditOpen = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  auditForm: {},
  detailForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productCategory: null,
    variety: null,
    plantingRecordNumber: null,
    auditStatus: null,
  },
  rules: {
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    productCategory: [
      { required: true, message: "产品类别不能为空", trigger: "change" }
    ],
    variety: [
      { required: true, message: "品种不能为空", trigger: "change" }
    ],
    plantingCycle: [
      { required: true, message: "种植周期(天)不能为空", trigger: "blur" }
    ],
    description: [
      { required: true, message: "追加事项不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "所属用户ID不能为空", trigger: "blur" }
    ],
    plantingRecordNumber: [
      { required: true, message: "农产品种植备案号不能为空", trigger: "blur" }
    ],
  },
  auditRules: {
    rejectReason: [
      { required: true, message: "审核意见不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules, auditForm, detailForm, auditRules } = toRefs(data)

/** 查询准许种植产品管理列表 */
function getList() {
  loading.value = true
  listPermit(queryParams.value).then(response => {
    permitList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    productId: null,
    productName: null,
    productCategory: null,
    variety: null,
    plantingCycle: null,
    description: null,
    userId: null,
    suitableLand: null,
    suitableTemperature: null,
    suitableMonths: null,
    plantingRecordNumber: null,
    qualificationEffectiveTime: null,
    qualificationExpirationTime: null,
    precautions: null,
    auditStatus: null,
    reviewer: null,
    reviewerId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("permitRef")
}

// 审核表单重置
function resetAudit() {
  auditForm.value = {
    cropId: null,
    productId: null,
    productName: null,
    productCategory: null,
    variety: null,
    plantingCycle: null,
    description: null,
    userId: null,
    suitableLand: null,
    suitableTemperature: null,
    suitableMonths: null,
    plantingRecordNumber: null,
    precautions: null,
    auditStatus: null,
    auditComment: null,
    rejectReason: null,
    reviewer: null,
    reviewerId: null,
    createTime: null,
    updateTime: null
  }
}

// 详情表单重置
function resetDetail() {
  detailForm.value = {
    cropId: null,
    productId: null,
    productName: null,
    productCategory: null,
    variety: null,
    plantingCycle: null,
    description: null,
    userId: null,
    suitableLand: null,
    suitableTemperature: null,
    suitableMonths: null,
    plantingRecordNumber: null,
    precautions: null,
    auditStatus: null,
    reviewer: null,
    reviewerId: null,
    createTime: null,
    updateTime: null
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.productId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加准许种植产品管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _productId = row.productId || ids.value
  getPermit(_productId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改准许种植产品管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["permitRef"].validate(valid => {
    if (valid) {
      if (form.value.productId != null) {
        updatePermit(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPermit(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _productIds = row.productId || ids.value
  proxy.$modal.confirm('是否确认删除准许种植产品管理编号为"' + _productIds + '"的数据项？').then(function() {
    return delPermit(_productIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ncpsy/permit/export', {
    ...queryParams.value
  }, `permit_${new Date().getTime()}.xlsx`)
}

/** 审核按钮操作 */
function handleAudit(row) {
  resetAudit()
  const _productId = row.productId
  getPermit(_productId).then(response => {
    auditForm.value = response.data
    auditOpen.value = true
  })
}

// 提交审核
function submitAudit(status) {
  proxy.$refs["auditFormRef"].validate(valid => {
    if (valid) {
      // 设置审核状态
      auditForm.value.auditStatus = status
      // 设置审核人信息
      auditForm.value.reviewer = userStore.nickName
      auditForm.value.reviewerId = userStore.id
      
      // 调用更新API
      updatePermit(auditForm.value).then(response => {
        console.log(status)
        if (status === '审核通过') {
          proxy.$modal.msgSuccess("审核通过")
        } else {
          proxy.$modal.msgSuccess("审核驳回")
        }
        auditOpen.value = false
        getList()
      }).catch(() => {
        // 审核失败处理
      })
    }
  })
}

/** 取消审核 */
function cancelAudit() {
  auditOpen.value = false
  resetAudit()
}

/** 详情按钮操作 */
function handleDetail(row) {
  resetDetail()
  const _productId = row.productId
  getPermit(_productId).then(response => {
    detailForm.value = response.data
    detailOpen.value = true
  })
}

/** 取消详情 */
function cancelDetail() {
  detailOpen.value = false
  resetDetail()
}

getList()
</script>
